package com.swift.authority.application.config.security;

import com.swift.authority.common.constant.CommonConstant;
import com.swift.authority.security.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.security.oauth2.provider.token.TokenEnhancerChain;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.ArrayList;
import java.util.List;

/**
 * 客户端 给我们一个授权码 服务器根据授权码去服务器中寻找资源，
 * 找到资源以后再返回给客户端
 *
 * @author Administrator
 * @version 1.0
 * @description 授权服务器配置 @EnableAuthorizationServer
 * @date 2022/07/02  14:33
 */
@Configuration
@EnableAuthorizationServer
public class AuthServerConfig extends AuthorizationServerConfigurerAdapter {
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserDetailsServiceImpl userDetailsService;
    @Autowired
    @Qualifier("jwtTokenStore")
    private TokenStore jwtTokenStore;
    @Autowired
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Autowired
    private JwtTokenEnhancer jwtTokenEnhancer;
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        // 将client的信息放入缓存，这里暂时先放在内存中
        clients.inMemory()
                //客户端id
                .withClient("newClient")
                //秘钥
                .secret(passwordEncoder.encode(CommonConstant.PWD_SALT))
                //通过重定向地址可以拿到授权码 采用密码模式就不需要授权码
                .redirectUris("http://localhost:8080/login")
                //当前授权码的授权范围
                .scopes("all")
                // accessToken失效时间
                .accessTokenValiditySeconds(60)
                //token刷新时间
                .refreshTokenValiditySeconds(86400)
                //自动授权
                .autoApprove(true)
                /**
                 *授权类型：
                 *  1 授权码模式：authorization_code
                 *  2 密码模式：password
                 */
                .authorizedGrantTypes("authorization_code","password");
    }

    /**
     *  密码模式
     * 1 权限控制配置 --> 2授权管理器 authenticationManager
     * 使用jwt后 就不需要在配置tokenStore
     * @param endpoints 授权信息
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //设置增强内容
        TokenEnhancerChain enhancerChain = new TokenEnhancerChain();
        List<TokenEnhancer> enhancerList = new ArrayList<>();
        //增强器
        enhancerList.add(jwtTokenEnhancer);
        //转换器
        enhancerList.add(jwtAccessTokenConverter);
        enhancerChain.setTokenEnhancers(enhancerList);

        endpoints
                .authenticationManager(authenticationManager)
                .userDetailsService(userDetailsService)
                //accessToken转成 jwtToken
                .tokenStore(jwtTokenStore)
                .accessTokenConverter(jwtAccessTokenConverter)
                .tokenEnhancer(enhancerChain);
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        //单点登录 获取秘钥 必须配置：身份认证
        security.tokenKeyAccess("isAuthenticated()");
    }
}
